package cn.kgc.springcloud.service.impl;

import cn.kgc.springcloud.client.TagClient;
import cn.kgc.springcloud.entity.Tag;
import cn.kgc.springcloud.vo.ClazzVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.springcloud.entity.Clazz;
import cn.kgc.springcloud.service.ClazzService;
import cn.kgc.springcloud.mapper.ClazzMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService{

    @Autowired(required = false)
    private ClazzMapper clazzMapper;

    @Autowired
    private TagClient tagClient;

    @Override
    public List<ClazzVO> getList() {

        List<Clazz> clazzes = clazzMapper.selectList(null);

        List<ClazzVO> collect = clazzes.stream().map(clazz -> {
            ClazzVO clazzVO = new ClazzVO();

            BeanUtils.copyProperties(clazz, clazzVO);
            Integer tagId = clazz.getTagid();
            // 根据标签id 查询标签详细信息
            Tag tag = tagClient.getById(tagId);
            clazzVO.setTag(tag);
            return clazzVO;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public Clazz addClazz(String name, MultipartFile file, Integer tagId) {

        Clazz clazz = new Clazz();
        clazz.setName(name);
        clazz.setTagid(tagId);

        // 获取文件名字
        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);  //  文件的扩展名 不包含.
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String lastName = uuid+"."+filenameExtension;
        clazz.setPath(lastName);
        //文件上传
        File f = new File("D:\\upload\\" + lastName);
        try {
            file.transferTo(f);
            clazzMapper.insert(clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return clazz;
    }
}




